package com.lebang.service.ybd;

import com.alibaba.fastjson.JSON;

import com.lebang.component.RedisClient;
import com.lebang.domain.ybd.MemberGoldConfig;
import com.lebang.domain.ybd.MemberGoldRecord;
import com.lebang.entity.RequestHeaders;
import com.lebang.example.ybd.MemberGoldConfigExample;
import com.lebang.mapper.ybd.MemberGoldRecordMapper;
import com.lebang.model.RequestUserInfo;
import com.lebang.model.Whether;
import com.lebang.model.ybd.Contrast;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * @Author: hwq
 * @Date: 2020/3/24 20:10
 * @Version 1.0
 */
@Service
public class MemberGoldConfigService extends BaseService<MemberGoldConfig, Integer, MemberGoldConfigExample> {
    @Autowired
    private MemberGoldRecordMapper recordMapper;
    private static final String BASE_KEY = "MemberGoldConfig";
    private static final String MEMBER_COUNT = "MEMBER_POINT_COUNT:";
//    @Autowired
//    private RedissonClient redissonClient;
    @Autowired
    private RedisClient redisCompont;
    //删除缓存
    public void delCache() {
        redisCompont.del(Contrast.SETTING_KEY);
    }

    public List<MemberGoldConfig> selectAll() {
        List<MemberGoldConfig> list;
        String str=redisCompont.hget(Contrast.SETTING_KEY,BASE_KEY);
        if(str==null){
            MemberGoldConfigExample appRunConfigExample = new MemberGoldConfigExample();
            appRunConfigExample.createCriteria().andHasDeletedEqualTo(Whether.NO.getDbIndex()).andEnableEqualTo(Whether.YES.getDbIndex());
            list = this.selectByExample(appRunConfigExample);
            if (list != null) {
                redisCompont.hset(Contrast.SETTING_KEY,BASE_KEY, JSON.toJSONString(list));
            }
        }else {
            list=JSON.parseArray(str,MemberGoldConfig.class);
        }
        return list;
//        RBucket<List<MemberGoldConfig>> bucket = redissonClient.getBucket(BASE_KEY);
//        if (bucket.get() != null) {
//            return bucket.get();
//        } else {
//            MemberGoldConfigExample appRunConfigExample = new MemberGoldConfigExample();
//            appRunConfigExample.createCriteria().andHasDeletedEqualTo(Whether.NO.getDbIndex()).andEnableEqualTo(Whether.YES.getDbIndex());
//            List<MemberGoldConfig> appRunConfigs = this.selectByExample(appRunConfigExample);
//            if (appRunConfigs != null) {
//                bucket.set(appRunConfigs);
//            }
//            return appRunConfigs;
//        }
    }

    public List<MemberGoldConfig> filter(List<MemberGoldConfig> list, RequestHeaders request) {
        list.forEach(s -> {
            Integer todayCount = this.getCount(request, s);
            if (todayCount >= s.getMaxReceiveCount()) {
                s.setStatus(-1);
            } else {
                s.setStatus(this.checkCd(s, request).intValue());
            }
        });
        return list;
    }

    /**
     * 验证该金币是否CD
     *
     * @param config
     * @param request
     * @return
     */
    public Long checkCd(MemberGoldConfig config, RequestHeaders request) {
        if(redisCompont.exists(EXPIRE_KEY + config.getId() + ":" + request.getUserid() )){
            return redisCompont.timetolive(EXPIRE_KEY + config.getId() + ":" + request.getUserid() );
        }else {
            return 0L;
        }

//        RBucket<String> expire = redissonClient.getBucket(EXPIRE_KEY + config.getId() + ":" + request.getMemberId() + request.getAppId());
//        if (expire.isExists()) {
//            return expire.remainTimeToLive();
//        } else {
//            return 0L;
//        }
    }

    /**
     * 金币减CD
     *
     * @param config
     * @param request
     * @return
     */
    public void subTime(MemberGoldConfig config, RequestHeaders request, Integer time) {
//        RBucket<String> expire = redissonClient.getBucket(EXPIRE_KEY + config.getId() + ":" + request.getMemberId() + request.getAppId());
//        if (expire.isExists()) {
//            Long ttl = expire.remainTimeToLive();
//            expire.expire((ttl - time*1000) >= 0 ? (ttl - time) : 1, TimeUnit.MILLISECONDS);
//        }
        String key=EXPIRE_KEY + config.getId() + ":" + request.getUserid() ;
        if(redisCompont.exists(key)){
            Long ttl = redisCompont.timetolive(key);
             redisCompont.expire(key,
                     (ttl - time) >= 0 ? (int) (ttl - time) : 1);
        }
    }

    /**
     * 获取某个金币配置今日完成数
     *
     * @param request
     * @return
     */
    public Integer getCount(RequestHeaders request, MemberGoldConfig config) {
        Optional<String> str=redisCompont.Optionalhget(this.getCountKey(config.getId()), request.getUserid());
//        RMap<String, Long> rMap = redissonClient.getMap(this.getCountKey(config.getId()), LongCodec.INSTANCE);
//        Optional<Long> count = Optional.ofNullable(rMap.get(request.getAppId() + request.getMemberId()));
        return str.map(Integer::parseInt).orElse(0);
    }

    private static final String EXPIRE_KEY = "MemberGold:EXPIRE_KEY:";

    /**
     * 今日领取金币次数+1
     *
     * @param request
     * @return
     */
    public void addCount(RequestHeaders request, MemberGoldConfig config) {
        redisCompont.hincrby(this.getCountKey(config.getId()), request.getUserid(),1L);
//        RMap<String, Long> rMap = redissonClient.getMap(this.getCountKey(config.getId()), LongCodec.INSTANCE);
//        rMap.addAndGet(request.getAppId()+request.getMemberId(),1L);
//        if(rMap.addAndGet(request.getAppId()+request.getMemberId(),1L)>=config.getMaxReceiveCount()){
//
//        }
//        RBucket<String> expire = redissonClient.getBucket(EXPIRE_KEY + config.getId() + ":" + request.getMemberId() + request.getAppId());
//        expire.set("1l", config.getCoolTime(), TimeUnit.SECONDS);
        redisCompont.setex(EXPIRE_KEY + config.getId() + ":" + request.getUserid(),"1l",config.getCoolTime());
    }

    public String getCountKey(Integer id) {
        LocalDate date = LocalDate.now();
        return MEMBER_COUNT + id + ":" + date.format(DateTimeFormatter.ISO_DATE);
    }

    /**
     * 领取金币奖励
     * @param config
     * @param request
     * @return
     */
    public MemberGoldRecord pull(MemberGoldConfig config, RequestHeaders request) {
        MemberGoldRecord record = new MemberGoldRecord();
        record.setCreateTime(LocalDateTime.now());
        record.setModifyTime(LocalDateTime.now());
        record.setHasDeleted(0);
        record.setMemberId(request.getUserid());
        record.setPoint(config.getPoint());
        record.setGoldId(config.getId());
        record.setCreateDate(LocalDate.now());
        record.setIpAddress(request.getIpAddr());
        record.setImei(request.getImei());
        record.setAppStore(request.getAppStore());
        record.setVersion(request.getVersion());
        record.setIsDouble(0);
        recordMapper.insertSelective(record);
        addCount(request,config);
        return record;
    }

    public MemberGoldRecord selectRecordById(Long recordId) {
        return recordMapper.selectByPrimaryKey(recordId);
    }

    public void pullDouble(MemberGoldRecord record) {
        record.setPoint(record.getPoint()+record.getPoint());
        record.setIsDouble(1);
        recordMapper.updateByPrimaryKeySelective(record);
    }
}
